// 用户数据模块
import store from '@/store'
import {
	sendMessage
} from '@/api/websocket.js'
import {
	EXPAND_MENU_TRUE,
	EXPAND_MENU_FALSE
} from '@/common/app.js'
import $api from '@/api/flag.js'
import app from '@/main.js'
const state = {
	isExpandMenu: uni.getStorageSync('isExpandMenu') || true, // h5 状态下侧边菜单栏是否展开
	leftWindowStyle: uni.getStorageSync('leftWindowStyle') || {
		width: EXPAND_MENU_TRUE,
		transitionDuration: '0.2s',
		transitionTimingFunction: 'ease',
		transitionDelay: '0s',
		transitionProperty: 'all',
	},
	getGame: [], // 首页游戏列表
	mycolect: [], // 收藏列表
	token: uni.getStorageSync('token') || '', // 用户token
	userInfo: uni.getStorageSync('userInfo') || {}, // 用户数据
	homeData: uni.getStorageSync('homeData') || {}, // 首页数据 （轮播图，游戏分类）
	userMoney: '',
	recycleTime: null,
	recycleTimeSecond: '',
	isGamePage: false,
	appIsLoading: true,
	depositOrderInfo: uni.getStorageSync('depositOrderInfo') || '',
	widthOrderInfo: uni.getStorageSync('widthOrderInfo') || '',
	theme: uni.getStorageSync('theme') || 'black',
	windowSize: uni.getStorageSync('windowSize') || {}, //包括屏幕宽高 
	activeTab: uni.getStorageSync('activeTab') || 0,
	deviceType: uni.getStorageSync('deviceType') || 'phone', //设备类型
}
const mutations = {
	// 保存设备类型
	saveDeviceType(state, data) {
		state.deviceType = data
		uni.setStorageSync('deviceType', data)
	},
	saveActiveTab(state, data) {
		state.activeTab = data
		uni.setStorageSync('activeTab', data)
	},
	saveWindowSize(state, data) {
		state.windowSize = data
		uni.setStorageSync('windowSize', data)
		if (data.windowWidth >= 768 && data.windowWidth <= 1024) {
			store.commit('app/setIsExpandMenu', true)
			store.commit('app/setLeftPageWidth')
		} else if (data.windowWidth > 1024) {
			store.commit('app/setIsExpandMenu', false)
			store.commit('app/setLeftPageWidth')
		}
	},
	saveTheme(state, data) {
		state.theme = data
		uni.setStorageSync('theme', data)
	},
	saveRecycleTimeSecond(state, data) {
		state.recycleTimeSecond = data
	},
	saveAppIsLoading(state, data) {
		state.appIsLoading = data
	},
	saveIndex(state, data) { // 保存登录信息 
		state.homeData = data
		if (data === '') return
		uni.setStorageSync('homeData', data)
	},
	setIsExpandMenu(state, data) {
		state.isExpandMenu = data
		uni.setStorageSync('isExpandMenu', data)
	},
	saveToken(state, data) {
		state.token = data
		if (data === '') return
		uni.setStorageSync('token', data)
	},
	setLeftPageWidth(state, data) { // 设置左侧菜单的宽度以及状态
		// #ifdef H5
		if (data === 'suoxiao') {
			uni.setLeftWindowStyle({
				width: '0px',
				overflow: 'hidden',
				transitionDuration: '0s',
			})
		} else if (data === 'huanyuan') {
			uni.setLeftWindowStyle({
				...state.leftWindowStyle,
				transitionDuration: '0s',
			})
		} else {
			let result = {
				transitionDuration: '0.2s',
				transitionTimingFunction: 'ease',
				transitionDelay: '0s',
				transitionProperty: 'all',
			}
			if (state.isExpandMenu) {
				result = {
					width: EXPAND_MENU_FALSE,
					...result
				}
			} else {
				result = {
					width: EXPAND_MENU_TRUE,
					...result
				}
			}
			uni.setLeftWindowStyle(result)
			state.leftWindowStyle = result
			uni.setStorageSync('leftWindowStyle', result)
			store.commit('app/setIsExpandMenu', !state.isExpandMenu)
		}
		// #endif
	},
	saveUserInfo(state, data) {
		state.userInfo = data
		if (data === '') return
		uni.setStorageSync('userInfo', data)
	},
	saveUserMoney(state, data) {
		state.userMoney = data
		// uni.setStorageSync('userMoney', data)
	},
	saveDepositOrderInfo(state, data) {
		state.depositOrderInfo = data
		uni.setStorageSync('depositOrderInfo', data)
	},
	saveWidthOrderInfo(state, data) {
		state.widthOrderInfo = data
		uni.setStorageSync('widthOrderInfo', data)
	},
	saveRecycleTime(state, data) {
		if (data) {
			state.recycleTime = data
			console.log('保存回收计时器')
		} else {
			console.log('停止回收计时器')
			clearTimeout(state.recycleTime)
			state.recycleTime = null
		}
	},
	saveGamePage(state, data) {
		state.isGamePage = data
	},
	callUserLogout(state, data) {
		uni.removeStorageSync('token');
		uni.removeStorageSync('userInfo');
		state.token = ''
		state.userInfo = ''
	},
}

const actions = {
	getNameCode({
		commit,
		state,
		getters,
		dispatch
	}) {
		const {
			GETNAMECODE
		} = $api
		return new Promise((resolve, reject) => {
			sendMessage({
				flag: GETNAMECODE
			})
			uni.$once(GETNAMECODE, (res) => {
				const {
					code,
					data
				} = res
				if (code === 1) {
					resolve(data)
				}
				resolve(false)
			})
		})
	},
	getRecycle({
		commit,
		state,
		getters,
		dispatch
	}, isShowToast = true) {
		console.log('开始回收')
		if (state.isGamePage && state.recycleTime) { // 在游戏界面并且有计时器不用回收了
			commit('saveRecycleTime', false)
			commit('saveRecycleTimeSecond', '')
			console.log('在游戏界面并且有计时器不用回收了')
			return
		}
		if (!state.isGamePage && state.recycleTime) { // 不在游戏界面并且有计时器
			console.log('不在游戏界面并且有计时器')
			return
		}
		if (isShowToast) {
			uni.showLoading()
		} else {
			commit('saveGamePage', false)
		}
		const {
			RECYCLE
		} = $api
		sendMessage({
			flag: RECYCLE,
			content: {
				type: 2
			}
		})
		uni.$once(RECYCLE, (res) => {
			uni.hideLoading()
			const {
				code,
				data
			} = res
			if (code === 1 && state.recycleTime) {
				console.log('调用成功了，还有倒计时需要清除')
				commit('saveRecycleTime', false)
			}
			// else if (code === 1 && data.balanceAll === 0) { //
			// 	console.log('客户没钱')
			// 	return
			// } 
			else if (code === 0 && !isShowToast && !data.second) {
				console.log('回收失败了，需要自动回收并且没有传剩余时间')
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				setTimeout(() => {
					return dispatch('getRecycle', false)
				}, 1000)
				// const recycleTime = setTimeout(() => {
				// 	console.log('倒计时结束')
				// 	dispatch('getRecycle', false)
				// }, 35000)
				// commit('saveRecycleTime', recycleTime)
			} else if (code === 0 && data.second && !isShowToast) {
				commit('saveRecycleTime', false)
				commit('saveRecycleTimeSecond', data.second)
				// app.$openInvite()
				let inteverval = setInterval(() => {
					if (state.isGamePage) { // 在游戏界面不需要回收了
						return
					}
					if (!state.recycleTimeSecond) { // 
						// app.$closeInvite()
						commit('saveRecycleTimeSecond', '')
						commit('saveRecycleTime', false)
						dispatch('getRecycle', false)
						return
					}
					console.log('state.recycleTimeSecond', state.recycleTimeSecond)
					let recycleTimeSecond = --state.recycleTimeSecond
					commit('saveRecycleTimeSecond', recycleTimeSecond)
				}, 1000)

				commit('saveRecycleTime', inteverval)
			}
			if (isShowToast) {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		})
	},
	getUserInfo({
		commit,
		state,
		getters
	}) {
		const {
			USERINFO
		} = $api
		sendMessage({
			flag: USERINFO,
		})
		uni.$once(USERINFO, (res) => {
			const {
				code,
				data
			} = res
			if (code === 1) {
				if (getters?.isLogin) {
					commit('saveUserInfo', data.userinfo)
					commit('saveUserMoney', data.userinfo.money)
				}
			}
		})
	},
	homeInit({
		commit,
		state,
		getters,
		dispatch
	}) {
		// if (getters.isLogin) {
		// 	dispatch('getUserInfo')
		// }
		const {
			GETGAME,
			INDEX,
			MYCOLECT
		} = $api
		sendMessage({
			flag: GETGAME
		})
		sendMessage({
			flag: INDEX
		})
		uni.$once(INDEX, (e) => {
			console.log('homeInit: ', e);
			if (e.code === 1) {
				// 根据后台配置的字段 设置默认主题 没有配置默认黑色主题
				const theme = e.data.theme ? e.data.theme : 'black';
				// #ifdef H5  
				document.documentElement.dataset.theme = theme
				// #endif 
				commit('saveTheme', theme)
				commit('saveIndex', e.data)
			}
		})
		uni.$on(GETGAME, (e) => {
			state.getGame = e.data
		})
	},

	getMycolect({
		commit
	}, data = {}) {
		const {
			MYCOLECT
		} = $api
		sendMessage({
			flag: MYCOLECT,
			content: data
		})
		uni.$once(MYCOLECT, (e) => {
			state.mycolect = e.data
		})
	},

	// 退出登录
	userLogout({
		commit
	}) {
		uni.showLoading()
		const {
			LOGOUT
		} = $api
		sendMessage({
			flag: LOGOUT,
		})
		uni.$once(LOGOUT, (res) => {
			uni.hideLoading()
			const {
				code,
				data
			} = res
			uni.removeStorageSync('token');
			uni.removeStorageSync('userInfo');
			uni.clearStorageSync();
			commit('saveToken', '')
			commit('saveUserInfo', '')
			uni.reLaunch({
				url: '/pages/auth/auth?type=0'
			})
		})
	}
}

const getters = {
	isLogin(state) {
		return state.token ? true : false;
	},
	isPC(state) {
		return state.windowSize.windowWidth > 768;
	},
	// PC端宽屏
	isBigPC(state) {
		return state.deviceType == 'pc' && state.windowSize.windowWidth >= 768;
	},
	// PC端窄屏
	isSmallPC(state) {
		return state.deviceType == 'pc' && state.windowSize.windowWidth < 768;
	},
	// Pad端宽屏
	idBigPad(state) {
		return state.deviceType == 'pad' && state.windowSize.windowWidth >= 768;
	},
	// Pad端窄屏
	isSmallPad(state) {
		return state.deviceType == 'pad' && state.windowSize.windowWidth < 768;
	},
	// 窄屏 宽高不可变（移动设备）
	isPhone(state) {
		return state.deviceType == 'phone';
	},
	// 宽屏
	bigScreen(state, getters) {
		return getters.isBigPC || getters.idBigPad;
	},
	// 窄屏
	smallScreen(state, getters) {
		return getters.isSmallPC || getters.isSmallPad || getters.isPhone;
	}

}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}